package user

import (
	"5title_gin/global"
	baseModel "5title_gin/internal/model"
	"5title_gin/internal/model/system/dept"
	"5title_gin/internal/model/system/roles"
	"5title_gin/internal/model/user"
	"5title_gin/pkg/db/crud"
	"5title_gin/pkg/db/pagination"
	"5title_gin/pkg/utils/converter"
	"5title_gin/pkg/utils/crypto"
	"fmt"
)

type UserService struct {
	userCrud     *crud.CRUD[user.UserModel]
	deptCrud     *crud.CRUD[dept.SysDept]
	userRoleCrud *crud.CRUD[roles.SysRoleUser]
}

func NewUserService() *UserService {
	return &UserService{
		userCrud:     crud.NewCRUD[user.UserModel](global.DB),
		deptCrud:     crud.NewCRUD[dept.SysDept](global.DB),
		userRoleCrud: crud.NewCRUD[roles.SysRoleUser](global.DB),
	}
}

// GetUserInfo 获取用户信息
func (s *UserService) GetUserInfo(userID uint) (user.UserVo, error) {
	// 查询用户信息
	userModel, err := s.userCrud.GetByID(userID)
	if err != nil {
		return user.UserVo{}, err
	}

	// 查询部门信息
	deptName := "未知部门"
	if userModel.DeptID > 0 {
		deptModel, err := s.deptCrud.GetByID(userModel.DeptID)
		if err == nil {
			deptName = deptModel.DeptName
		}
	}

	// 构造返回结构
	return user.UserVo{
		UserModel: userModel,
		DeptName:  deptName,
	}, nil
}

// CreateUser 创建用户
func (s *UserService) CreateUser(user user.UserModel) error {
	password, err := crypto.GenerateFromPassword("123456")
	if err != nil {
		return err
	}
	user.Password = password
	user.Status = 2
	user.Email = "xxxxxxx@mall.com"
	if err := s.userCrud.Create(&user); err != nil {
		return err
	}
	if err := s.userRoleCrud.Create(&roles.SysRoleUser{
		RoleID: user.RoleID,
		UserID: user.ID,
	}); err != nil {
		return err
	}
	return nil
}

// UpdateUserInfo 更新用户信息
func (s *UserService) UpdateUserInfo(model user.UserModel) error {
	// 创建一个新的模型，只包含要更新的字段
	updateModel := user.UserModel{
		Username:  model.Username,
		Nickname:  model.Nickname,
		Mobile:    model.Mobile,
		Email:     model.Email,
		Sex:       model.Sex,
		Status:    model.Status,
		DeptID:    model.DeptID,
		RoleID:    model.RoleID,
		Avatar:    model.Avatar,
		Des:       model.Des,
		LastLogin: model.LastLogin,
	}

	// 使用UpdateByID方法更新，只会更新非零值字段
	if err := s.userCrud.UpdateByID(model.ID, updateModel); err != nil {
		return fmt.Errorf("更新用户信息失败: %v", err)
	}
	// 更新用户角色关系
	userRole, err := s.userRoleCrud.GetAll().Where("user_id", model.ID).Find()
	if err != nil {
		return err
	}

	if len(userRole) > 0 {
		// 角色已存在，检查是否需要更新
		if userRole[0].RoleID != model.RoleID {
			if err := s.userRoleCrud.Updates(&userRole[0], map[string]any{"role_id": model.RoleID}); err != nil {
				return err
			}
		}
	} else {
		// 创建新的用户角色关系
		if err := s.userRoleCrud.Create(&roles.SysRoleUser{
			RoleID: model.RoleID,
			UserID: model.ID,
		}); err != nil {
			return err
		}
	}

	return nil
}

// GetUserList 获取用户列表
func (s *UserService) GetUserList(pageInfo baseModel.PageInfo) ([]*user.UserVo, int64, error) {
	// 1. 分页查询用户模型列表
	list, total, err := pagination.QueryList[user.UserModel](user.UserModel{}, pagination.QueryOption{
		PageInfo: pageInfo,
		Likes:    []string{"username", "nickname"},
		Debug:    true,
	})
	if err != nil {
		return nil, 0, fmt.Errorf("查询用户列表失败: %v", err)
	}
	// 手动创建VO列表，确保UserModel指针不为nil
	voList := make([]*user.UserVo, len(list))
	for i, userModel := range list {
		// 创建一个新的UserVo，并确保UserModel指针有效
		voList[i] = &user.UserVo{
			UserModel: userModel, // 这里userModel已经是指针类型
			DeptName:  "",        // 先设置为空字符串，后面会填充
		}
	}
	depts, err := s.deptCrud.GetAll().Find()
	if err != nil {
		return nil, 0, fmt.Errorf("查询部门列表失败: %v", err)
	}

	options := converter.FillOptions{
		EntityIDField:   "ID",
		EntityNameField: "DeptName",
	}
	if err := converter.FillNameField(voList, depts, "DeptID", "DeptName", options); err != nil {
		return nil, 0, fmt.Errorf("填充部门名称失败: %v", err)
	}

	return voList, total, nil
}

// DeleteUser 删除用户
func (s *UserService) DeleteUser(userId uint) error {
	if err := s.userCrud.DeleteByID(userId); err != nil {
		return err
	}
	if err := s.userRoleCrud.DeleteByID(userId); err != nil {
		return err
	}
	return nil
}
